package net.fiodor.log.channel {
	import flash.net.LocalConnection;

	/**
	 * @author Tomasz Swierszcz, 
	 * email: tomasz.swierszcz@dreamlab.pl
	 */

	public class Debug {

		private static var lc : LocalConnection;
		private static var level : Number = 0;

		public static var DEBUG : Number = 0;
		public static var INFO : Number = 1;
		public static var WARN : Number = 2;
		public static var ERROR : Number = 3;
		public static var FATAL : Number = 4;

		
		public function Debug() {
        // can't make an instance
		}

		/**
		 *	Clears the debug panel of any messages.
		 */
		public static function clear() : void {
        
			lc = new LocalConnection();
			lc.send("_trace", "clear");
		}    

		/**
		 *	Sets the default level of any future messages.
		 *	@param pLvl The level to set. Values are 0 through 4, or Debug.Debug, Debug.INFO, Debug.WARN, Debug.ERROR, Debug.FATAL.
		 */
		public static function setLevel(pLvl : Number) : void {
			level = pLvl;
		}

		/**
		 *	Traces any value to the debug panel, with an optional message level.
		 *	@param pMsg The value to trace.
		 *	@param pLvl Optional. The level for this message. Values are 0 through 4, or Debug.Debug, Debug.INFO, Debug.WARN, Debug.ERROR, Debug.FATAL.
		 */
		public static function trace(pMsg : Object, pLvl : Number) : void {
			
			var tLvl : Number  = pLvl;
        	
			lc = new LocalConnection();
			lc.send("_trace", "trace", pMsg, tLvl);
		}

		/**
		 *	Recursively traces an object's value to the debug panel.
		 *	@param o The object to trace.
		 *	@param pRecurseDepth Optional. How many levels deep to recursively trace. Defaults to 0, which traces only the top level value.
		 *	@param pLvl Optional. The level for this message. Values are 0 through 4, or Debug.Debug, Debug.INFO, Debug.WARN, Debug.ERROR, Debug.FATAL.
		 *	@param pIndent Optional. Number of spaces to indent each new level of recursion.
		 */
		public static function traceObject(o : Object, pRecurseDepth : Number = 0, pLvl : Number = 1024, pIndent : Number = 0) : void {
			var recurseDepth : Number = pRecurseDepth;
			var indent : Number = pIndent;
			var tLvl : Number  = pLvl;
		
			
		
			for (var prop:String in o) {
				var lead : String = "";
				for (var i : Number = 0;i < indent; i++) {
					lead += "    ";
				}
				
				var obj : String = o[prop].toString();
				
				if (o[prop] is Array) {
					obj = "[Array]";
				}
				if (obj == "[object Object]") {
					obj = "[Object]";
				}
				Debug.trace(lead + prop + ": " + obj, tLvl);
				if (recurseDepth > 0) {
					traceObject(o[prop], recurseDepth - 1, tLvl, indent + 1);
				}
			
			}	
			
		}
		
	}
}
